import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:lmmi/common/index.dart';
import 'package:intl/intl.dart';

class EmailInputPage extends ConsumerStatefulWidget {
  final TimeCapsule timeCapsule;

  const EmailInputPage({super.key, required this.timeCapsule});

  @override
  ConsumerState<EmailInputPage> createState() => _EmailInputPageState();
}

class _EmailInputPageState extends ConsumerState<EmailInputPage> {
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _backupEmailController = TextEditingController();
  bool _showSuccessDialog = false;
  bool _hideInputElements = false;
  bool _showFinalDialog = false;

  @override
  void dispose() {
    _emailController.dispose();
    _backupEmailController.dispose();
    super.dispose();
  }

  // 保存时间胶囊
  Future<void> _saveTimeCapsule() async {
    final email = _emailController.text.trim();
    final backupEmail = _backupEmailController.text.trim();

    if (email.isEmpty) {
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(const SnackBar(content: Text('Please enter your email')));
      return;
    }

    if (backupEmail.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Please enter your backup email')),
      );
      return;
    }

    // 更新时间胶囊的邮箱信息
    final updatedTimeCapsule = widget.timeCapsule.copyWith(
      email: email,
      backupEmail: backupEmail,
    );

    try {
      // 先隐藏输入元素
      setState(() {
        _hideInputElements = true;
      });

      // 使用现有的provider保存时间胶囊
      await ref
          .read(timeCapsuleProvider.notifier)
          .createTimeCapsule(updatedTimeCapsule);

      if (mounted) {
        // 显示成功弹窗
        setState(() {
          _showSuccessDialog = true;
        });
      }
    } catch (e) {
      if (mounted) {
        // 如果失败，恢复输入元素显示
        setState(() {
          _hideInputElements = false;
        });
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Failed to create time capsule: $e')),
        );
      }
    }
  }

  String _formatDate(String dateString) {
    try {
      DateTime date = DateTime.parse(dateString);
      return DateFormat('MMMM d, yyyy').format(date);
    } catch (e) {
      debugPrint('Error parsing date: $e');
      return dateString;
    }
  }

  // 处理弹窗确认按钮点击
  void _handleDialogConfirm() async {
    // 隐藏第一个弹窗，显示第二个弹窗
    setState(() {
      _showSuccessDialog = false;
      _showFinalDialog = true;
    });

    // 暂停1.5秒后返回主页面
    await Future.delayed(const Duration(milliseconds: 1500));

    if (mounted) {
      context.navigateTo(AppRoutes.main);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      // resizeToAvoidBottomInset: false,
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back_ios_new_rounded,
            color: Colors.black,
            size: 22.sp,
          ),
          onPressed: () => context.goBack(),
        ),
      ),
      body: GestureDetector(
        onTap: () {
          FocusScope.of(context).unfocus();
        },
        child: SingleChildScrollView(
          child: Container(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(MyImages.homeBg),
                fit: BoxFit.fill,
              ),
            ),
            child: Stack(
              children: [
                // 主要内容
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 12.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: _hideInputElements
                        ? MainAxisAlignment.center
                        : MainAxisAlignment.start,
                    children: [
                      if (!_hideInputElements) SizedBox(height: 77.h),
                      // emailBg 图片
                      Center(
                        child: Container(
                          width: 348.w,
                          height: 348.h,
                          decoration: BoxDecoration(
                            image: DecorationImage(
                              image: AssetImage(MyImages.emailBg),
                              fit: BoxFit.contain,
                            ),
                          ),
                        ),
                      ),

                      // 输入框和按钮等元素，只在未隐藏时显示
                      if (!_hideInputElements) ...[
                        SizedBox(height: 13.h),
                        Container(
                          width: 344.w,
                          height: 52.h,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(10.r),
                          ),
                          child: Padding(
                            padding: EdgeInsets.symmetric(horizontal: 12.w),
                            child: Center(
                              child: TextField(
                                controller: _emailController,
                                decoration: InputDecoration(
                                  hintText: 'Enter your email',
                                  border: InputBorder.none,
                                  enabledBorder: InputBorder.none,
                                  focusedBorder: InputBorder.none,
                                  hintStyle: TextStyle(
                                    color: Colors.black.withValues(alpha: 0.28),
                                    fontSize: 14.sp,
                                    fontFamily: 'PingFang SC',
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),

                        SizedBox(height: 13.h),
                        Container(
                          width: 344.w,
                          height: 52.h,
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(10.r),
                          ),
                          child: Padding(
                            padding: EdgeInsets.symmetric(horizontal: 12.w),
                            child: Center(
                              child: TextField(
                                controller: _backupEmailController,
                                decoration: InputDecoration(
                                  hintText: 'Enter your backup email',
                                  border: InputBorder.none,
                                  enabledBorder: InputBorder.none,
                                  focusedBorder: InputBorder.none,
                                  hintStyle: TextStyle(
                                    color: Colors.black.withValues(alpha: 0.28),
                                    fontSize: 14.sp,
                                    fontFamily: 'PingFang SC',
                                    fontWeight: FontWeight.w500,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ),
                        SizedBox(height: 13.h),
                        // 提示文字
                        SizedBox(
                          width: 296.w,
                          height: 99.h,
                          child: Text(
                            'Whether it\'s today, tomorrow, or a year from now, the time capsule will preserve those moments you don\'t want to lose, becoming a lasting surprise in your life.',
                            style: TextStyle(
                              color: const Color(0xFFFF9400),
                              fontSize: 14.sp,
                              fontFamily: 'Port',
                              fontWeight: FontWeight.w400,
                              height: 1.43.h,
                            ),
                          ),
                        ),

                        SizedBox(height: 13.h),
                        GestureDetector(
                          onTap: _saveTimeCapsule,
                          child: Container(
                            width: 348.w,
                            height: 54.h,
                            decoration: ShapeDecoration(
                              gradient: LinearGradient(
                                begin: Alignment(0.00, 0.50),
                                end: Alignment(1.00, 0.50),
                                colors: [
                                  const Color(0xFFFF8C00),
                                  const Color(0xFFF8FFC7),
                                ],
                              ),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(60.r),
                              ),
                            ),
                            child: Center(
                              child: Text(
                                'Send',
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 16.sp,
                                  fontFamily: 'PingFang SC',
                                  fontWeight: FontWeight.w600,
                                  height: 1.h,
                                ),
                              ),
                            ),
                          ),
                        ),

                        Spacer(),
                        SizedBox(height: 35.h),
                      ],
                    ],
                  ),
                ),

                // 成功弹窗
                if (_showSuccessDialog)
                  Container(
                    color: Colors.black.withValues(alpha: 0.5),
                    child: Center(
                      child: Container(
                        width: 323.w,
                        height: 364.h,
                        decoration: ShapeDecoration(
                          color: Colors.white,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20.r),
                          ),
                        ),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            // 图片
                            Image.asset(
                              MyImages.timeCapsuleGo,
                              width: 171.w,
                              height: 171.h,
                            ),

                            SizedBox(height: 20.h),

                            // 文字
                            SizedBox(
                              width: 268.w,
                              child: Text(
                                'The Letter Has Traveled Through Time to the Future and Will Meet You Someday.',
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 16.sp,
                                  fontFamily: 'PingFang SC',
                                  fontWeight: FontWeight.w600,
                                  height: 1.12.h,
                                  letterSpacing: 0.23,
                                ),
                              ),
                            ),

                            SizedBox(height: 30.h),

                            // 按钮
                            GestureDetector(
                              onTap: _handleDialogConfirm,
                              child: Container(
                                width: 295.w,
                                height: 51.h,
                                padding: EdgeInsets.symmetric(horizontal: 10.w),
                                decoration: ShapeDecoration(
                                  gradient: LinearGradient(
                                    begin: Alignment(0.00, 0.50),
                                    end: Alignment(1.00, 0.50),
                                    colors: [
                                      const Color(0xFFFF8C00),
                                      const Color(0xFFF8FFC7),
                                    ],
                                  ),
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(30.r),
                                  ),
                                  shadows: [
                                    BoxShadow(
                                      color: const Color(0x190D0A14),
                                      blurRadius: 14.r,
                                      offset: const Offset(0, 8),
                                      spreadRadius: 0,
                                    ),
                                  ],
                                ),
                                child: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  children: [
                                    Text(
                                      'Got it',
                                      style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 18.sp,
                                        fontFamily: 'Pangram',
                                        fontWeight: FontWeight.w500,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),

                // 最终弹窗
                if (_showFinalDialog)
                  Container(
                    color: Colors.black.withValues(alpha: 0.5),
                    child: Center(
                      child: _buildSuccessDialog(
                        widget.timeCapsule.createDate,
                        _emailController.text,
                        widget.timeCapsule.openDate,
                      ),
                    ),
                  ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildSuccessDialog(String createDate, String email, String sendDate) {
    return Container(
      width: 340.w,
      height: 435.h,
      decoration: BoxDecoration(
        image: DecorationImage(image: AssetImage(MyImages.successfulBg)),
      ),
      child: Column(
        children: [
          SizedBox(height: 125.h),
          Text(
            'To Be Delivered On: ${_formatDate(sendDate)}',
            textAlign: TextAlign.center,
            maxLines: 2,
            style: TextStyle(
              color: Colors.black,
              fontSize: 12.sp,
              fontFamily: 'PingFang SC',
              fontWeight: FontWeight.w600,
              decoration: TextDecoration.underline,
              height: 1.23.h,
            ),
          ),
          SizedBox(height: 8.h),
          Text(
            'Send To: $email',
            textAlign: TextAlign.center,
            style: TextStyle(
              color: Colors.black,
              fontSize: 12.sp,
              fontFamily: 'PingFang SC',
              fontWeight: FontWeight.w600,
              decoration: TextDecoration.underline,
              height: 1.23.h,
            ),
          ),
          SizedBox(height: 8.h),
          Text(
            'Sending: ${_formatDate(createDate)}',
            textAlign: TextAlign.center,
            style: TextStyle(
              color: Colors.black,
              fontSize: 12.sp,
              fontFamily: 'PingFang SC',
              fontWeight: FontWeight.w600,
              decoration: TextDecoration.underline,
              height: 1.23.h,
            ),
          ),
        ],
      ),
    );
  }
}
